package com.hxx.common.core.wcontour.read;

import com.hxx.common.core.wcontour.util.GridRarefyUtil;
import com.hxx.common.core.wcontour.base.TrainData;
import org.meteoinfo.common.DataConvert;
import org.meteoinfo.data.GridData;
import org.meteoinfo.data.meteodata.MeteoDataInfo;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.math.BigDecimal;

/**
 * 雷达bin数据读取
 *
 * @author hxd
 */
public class RadarBinUtil {

    /**
     * 点数抽稀倍数
     */
    private static final int rarefy = 1;

    public static TrainData read(File jsonFile) {
        MeteoDataInfo m = new MeteoDataInfo();
        m.openMICAPSData(jsonFile.getPath());
        GridData gridData = m.getGridData();
        double[] xArray = gridData.getXArray();
        double[] yArray = gridData.getYArray();
        double[][] data = getGridData_LonLat(jsonFile.getPath(), yArray.length, xArray.length);
        double[][] convertData = new double[data[0].length][data.length];
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[0].length; j++) {
                convertData[j][i] = data[i][j];
            }
        }
        TrainData trainData = new TrainData();
        trainData.set_X(xArray);
        trainData.set_Y(yArray);
        trainData.setData(convertData);
        trainData.setSize(new int[]{xArray.length, yArray.length});
        // 抽稀
        GridRarefyUtil.rarefy(trainData, rarefy);
        return trainData;
    }


    private static double[][] getGridData_LonLat(String fileName, int yNum, int xNum) {
        try {
            RandomAccessFile br = new RandomAccessFile(fileName, "r");
            int n = yNum * xNum;
            byte[] bytes = new byte[n];
            br.skipBytes(1024);
            br.read(bytes);
            br.close();

            double[][] gData = new double[yNum][xNum];
            for (int i = 0; i < yNum; i++) {
                for (int j = 0; j < xNum; j++) {
                    // 雷达数据是从左上角开始，每层的数据从起始点（左上角）开始，按维向（纬度y）减小写每行的经向（经度x增大）数据，需要转换为左下角开始
                    int value = DataConvert.byte2Int(bytes[(yNum - i - 1) * xNum + j]);
                    double dbz = new BigDecimal(value - 66).divide(new BigDecimal(2)).doubleValue();
                    if (dbz <= 0) {
                        dbz = 0;
                    }
                    gData[i][j] = dbz;
                }
            }
            return gData;
        } catch (IOException e) {
            return null;
        }
    }
}
